package net.vsame.url2sql.render;

import java.io.IOException;
import java.io.PrintWriter;

import net.vsame.url2sql.helper.Url2SqlContext;
import net.vsame.url2sql.helper.WebHelper;
import net.vsame.url2sql.url.impl.UrlConfig;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;

public class JsonRender extends Render{

	private static final long serialVersionUID = 2180837861197629103L;

	@Override
	public void render() {
		Url2SqlContext c = WebHelper.getContext();
		response.setContentType("application/x-javascript; charset=" + encoding);
		PrintWriter out = null;
		try {
			out = response.getWriter();
			out.write(getJosn(c));
			out.flush();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if(out != null){
				out.close();
			}
		}
	}
	
	public static String getJosn(Url2SqlContext context) {
		UrlConfig c = context.getUrlConfig();
		if(context.hasError()){
			//已包含错误
		}else if(c == null){
			//API不存在
			context.put404();
		}else if(c.getStatus() != null){
			context.putError(-7, c.getStatus());
		}
		return JSON.toJSONString(context.getDatas(), SerializerFeature.WriteDateUseDateFormat, SerializerFeature.DisableCircularReferenceDetect);
	}

}
